<template>
    <div style="backgroundcolor: rgb(245, 245, 245);color:#222;width:50%">
        <div class="risk-bound-cfg">
            <span style="width: 75px"> 范围属性： </span>
            <el-select v-model="investGroupType" size="mini" :disabled="isDisabled">
                <el-option
                    v-for="item in boundType"
                    :value="item.dictKey"
                    :key="item.dictKey"
                    :label="item.dictKey + ' ' + item.dictKeyName"
                ></el-option>
            </el-select>
            <!-- category -->
        </div>
        <div class="risk-bound-tree" :style="{ height: operatePanelHeight }" style="minHeight: 300px;">
            <div style="padding:2px 0">
                <el-row :gutter="10">
                    <el-col :span="4">
                        <el-select v-model="sqlSpliceType" placeholder="请选择" size="mini" @change="handleSqlSpliceType">
                            <el-option v-for="(value, key) in conditionRelation" :key="key" :label="key + ' ' + value" :value="key + ' ' + value">
                            </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="6">
                        <el-select v-model="fundDynamicGroupBounds.boundCode" placeholder="证券范围" @change="handleOriginalBoundConfig" size="mini">
                            <el-option value="-1" label=" " key="-1"></el-option>
                            <el-option
                                v-for="item in originList"
                                :key="item.boundCode"
                                :label="item.boundCode + '' + item.boundName"
                                :value="item.boundCode"
                            >
                            </el-option>
                        </el-select>
                    </el-col>

                    <el-col :span="4">
                        <el-select v-model="fundDynamicGroupBounds.compareType" placeholder="比较方向" size="mini">
                            <el-option v-for="value in compareTypes" :key="value" :label="value + '  ' + CompareDirection[value]" :value="value">
                            </el-option>
                        </el-select>
                    </el-col>

                    <el-col :span="4">
                        <div v-show="webShowType === '0'">
                            <vxe-pulldown ref="showTypeDown">
                                <template #default>
                                    <yh-input
                                        v-model="boundValueShow"
                                        placeholder="请选择"
                                        @focus="showTypeFocusEvent"
                                        class="service-type-input"
                                        size="mini"
                                    ></yh-input>
                                </template>
                                <template #dropdown>
                                    <div class="my-dropdown" style="width: 200px">
                                        <div class="accountControlValue-search">
                                            <i class="el-icon-search" style="cursor: pointer"></i>
                                            <yh-input
                                                v-model="boundValueSearchInput"
                                                @keyup.native="boundValueSearch"
                                                placeholder="请选择"
                                                size="mini"
                                            ></yh-input>
                                        </div>
                                        <div>
                                            <yh-checkbox-group v-model="fundDynamicGroupBounds.boundValues" @change="handleBoundValueChange">
                                                <yh-checkbox v-for="item in dictsTemp" :key="item.dictKey" :label="item.dictKey">
                                                    {{ item.dictKey + '  ' + item.dictKeyName }}</yh-checkbox
                                                >
                                            </yh-checkbox-group>
                                        </div>
                                    </div>
                                </template>
                            </vxe-pulldown>
                        </div>
                        <!-- 计数器-整数 -->
                        <yh-input-number
                            v-model="form.boundValueNum"
                            controls-position="right"
                            @change="handleBoundValueChange1"
                            v-if="webShowType === '1'"
                            size="mini"
                        ></yh-input-number>
                        <div v-show="webShowType === '2' && !separateValid" style="display: flex">
                            <el-input disabled style="width: 80px" size="mini" placeholder="" v-model="transValuesShow"></el-input>
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="selectKeyValue2Click" style="margin-left: 2px">
                            </el-button>
                        </div>
                        <el-date-picker
                            v-model="boundValueDate"
                            type="date"
                            placeholder="选择日期时间"
                            size="mini"
                            value-format="yyyyMMdd"
                            format="yyyyMMdd"
                            @change="handleBoundValueChange2"
                            v-show="webShowType === '3'"
                        >
                        </el-date-picker>
                        <el-select v-model="boundValueSelect" v-show="webShowType === '4'" @change="handleBoundValueChange3" size="mini">
                            <el-option
                                v-for="item in dictsTemp"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                        <!-- 计数器-小数 -->
                        <el-input-number
                            v-model="form.boundValueNum"
                            controls-position="right"
                            :disabled="showData"
                            :step="1"
                            :precision="6"
                            :max="10000000000000"
                            @change="handleBoundValueChange1"
                            v-if="webShowType === '5'"
                            size="mini"
                        ></el-input-number>
                    </el-col>
                    <el-col :span="4">
                        <yh-checkbox
                            v-model="separateValid"
                            :disabled="!currentConfigSeparateValid"
                            v-show="!notShowSingleControl"
                            style="margin-right: 5px"
                            >单独控制</yh-checkbox
                        >
                    </el-col>
                    <el-col :span="2">
                        <el-button
                            icon="el-icon-circle-plus-outline"
                            type="primary"
                            style="margin-right: 5px"
                            @click="handleAddConfig"
                            size="mini"
                            title="添加"
                        ></el-button>
                    </el-col>
                </el-row>
            </div>
            <div class="risk-bound-tree-show">
                <el-row style="height:100%">
                    <el-col :span="22" style="height:100%">
                        <div
                            class="content"
                            style="width: 100%; height: 100%; background-color: white; border: 1px solid #ccc;border-radius:5px;overflow:auto"
                        >
                            <el-tree
                                ref="tree"
                                id="tree"
                                :data="originalRenderTree"
                                :props="defaultProps"
                                @node-click="handleBoundNodeClick"
                                :expand-on-click-node="false"
                                node-key="configId"
                                :check-on-click-node="true"
                            ></el-tree>
                        </div>
                    </el-col>
                    <el-col :span="2" style="display: flex; flex-direction: column; align-items: center">
                        <el-button icon="el-icon-check" size="mini" type="primary" title="编辑" @click="handleUpdateConfig" style="margin: 5px 0px" />
                        <el-button icon="el-icon-minus" size="mini" type="danger" title="删除配置" @click="handleDeleteConfig" />
                        <!-- <div style="display: investGroupType === '3' ? 'flex' : 'none'">
              <el-button type="primary" icon="exclamation-circle" title="校验配置" style="margin-top: 5px" @click="handleCheckConfig" />
            </div> -->
                    </el-col>
                </el-row>
            </div>
        </div>
        <!-- 穿梭框 -->
        <div>
            <yh-dialog drag :visible.sync="editLargeDataDialog.visible" width="800px" v-loading="loading" append-to-body>
                <div style="height: fit-content">
                    <RiskTrantable
                        leftPlaceholder="编号/名称"
                        rightPlaceholder="编号/名称"
                        :leftColumns="tranColumns"
                        :rightColumns="tranColumns"
                        :leftTableData="leftTranData"
                        :rightTableData="rightTranData"
                        :leftSearchNames="['dictKey', 'dictKeyName']"
                        indexKey="dictKey"
                        ref="tranTable"
                        sort="dictKeyName"
                    />
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="mini" @click="editLargeDataDialogClosed"> 取 消 </el-button>
                    <el-button size="mini" type="primary" @click="editLargeDataDialogConfirm">确 定 </el-button>
                </div>
            </yh-dialog>
        </div>
    </div>
</template>

<script lang="ts">
import RiskTrantable from '@/common/components/risk-trantable.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { DialogVO } from '@yhfin/biz';
import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import Dict from '@/pages/baseparam/dict/index';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

export interface dynamicDataReqVO {
    dynamicCode?: string;
    boundCode?: string;
    boundValues?: any[];
    compareType?: string; // 比较方向
    boundValueNames?: any[]; //
    boundGroupValid?: boolean; // 是否是组配置
    parentId?: number;
    configId?: number;
    showBoundExtend?: boolean;
    specialBranch?: boolean;
    separateValid?: boolean; // 是否同申报
    sqlSpliceType?: string; // sql拼接符
    groupType?: string; // 范围配置组控制类型
}

@Component({
    name: 'ItemBoundSetting',
    components: {
        RiskTrantable,
    },
})
//  * 组件属性：
//  * stockBound：范围配置集合
//  * operate：操作类型 新增/查看/编辑
//  * investGroupType：范围属性 必须
//  * settingValue：回调函数 设置后的值
export default class ItemBoundSetting extends Vue {
    @Prop() stockBound: any;
    @Prop() riskEntryBranchList!: any;
    @Prop() operate: string;
    @Prop() investGroupType: string;
    // 单独控制单选框是否显示
    @Prop({ default: true }) notShowSingleControl: boolean;
    @Prop() operatePanelHeight?: string;
    @Prop() isDisabled: boolean;
    @Emit('onHandleOperateOver')
    private settingValue(value) {
        return value;
    }
    Dict: any = new Dict();
    // 范围属性组
    private boundType: any[] = [];

    private originList: any = [];
    private editLargeDataDialog: DialogVO = new DialogVO();

    // 输入框类型
    private webShowType: string = '5';
    // 比较类型
    private compareTypes: any[] = [];
    // 单独控制
    private separateValid: boolean = false;

    // 单独控制单选框是否禁用
    private currentConfigSeparateValid: boolean = false;

    // 多选框所选值回显
    private boundValueShow: string = '';

    // 多选框选项
    private dicts = [];
    // 多选框临时选项
    private dictsTemp = [];

    private transValuesShow: string = '';
    // 日期选择期绑定值
    private boundValueDate: string = '';
    // 单选框绑定值
    private boundValueSelect: string = '';

    // 多选框搜索输入值
    private boundValueSearchInput: string = '';

    // 穿梭框显示值
    private boundTransValueShow: string = '';

    // sql拼接字段符转义
    private conditionRelation: any = [];

    private sqlSpliceType: string = '0 并且';

    private leftTranData: any[] = [];
    private rightTranData: any[] = [];
    private tranColumns: any[] = [
        {
            label: '编号',
            prop: 'dictKey',
            width: 80,
        },
        {
            label: '名称',
            prop: 'dictKeyName',
            width: 165,
        },
    ];

    // // 1为可添加子节点的节点，2为不可添加子节点的节点
    // private boundNodeFlag: number = 1;

    private parentId: number = 0;

    private configId: number = 2;

    private originalConfigList: any = []; // 配置数据集合

    // 树形结构数据
    private boundTreeData: any = [];

    // 选中树的子节点
    private selectedBranchConfig: dynamicDataReqVO = {};

    private currentTreeNode: any = null;
    private allParentTreeNodes: any = []; // 所有的父级节点 便于全部展开
    private currentOpenTreeNode: any[] = []; // 当前展开的节点
    private originalRenderTree: any[] = [];
    private operateType: string = 'edit';
    // 计数器输入框绑定值
    private form = {
        boundValueNum: undefined,
    };

    private fundDynamicGroupBounds: dynamicDataReqVO = {
        // 证券范围配置项
        dynamicCode: '',
        boundCode: '-1',
        boundValues: [],
        compareType: '', // 比较方向
        boundValueNames: [], //
        boundGroupValid: true,
        parentId: 0,
        configId: 2,
        showBoundExtend: false,
        specialBranch: false,
        separateValid: false, // 是否同申报
        sqlSpliceType: '0', // sql拼接符
        groupType: '3', // 范围配置组控制类型
    };

    private fundDynamicGroupBoundsBackup: dynamicDataReqVO = {
        // 证券范围配置项
        dynamicCode: '',
        boundCode: '-1',
        boundValues: [],
        compareType: '', // 比较方向
        boundValueNames: [], //
        boundGroupValid: true,
        parentId: 0,
        configId: 2,
        showBoundExtend: false,
        specialBranch: false,
        separateValid: false, // 是否同申报
        sqlSpliceType: '0', // sql拼接符
        groupType: '3', // 范围配置组控制类型
    };

    defaultProps = {
        children: 'children',
        label: 'label',
    };

    CompareDirection = this.Dict.CompareDirection;
    private categorys: any[] = [];
    originListlist: any[] = [];

    created() {
        this.conditionRelation = this.Dict.conditionRelation;
        // 范围属性
        this.boundType = DictionConstUtil.PojoToList(this.Dict.boundType);
        // 指标类型
        this.categorys = DictionConstUtil.PojoToList(this.Dict.Category);
    }

    // async mounted() {
    //     // 获取范围配置信息
    //     // let list: any = await DictionConstUtil.FNBoundCfg();
    //     // // 配置数据集合
    //     // this.originalConfigList = JSON.parse(JSON.stringify(this.stockBound || []));
    //     // // 处理操作类型
    //     // this.operateBoundCfg(this.operateType, this.originalConfigList);
    //     // // 设置值
    //     // this.fundDynamicGroupBounds.groupType = this.investGroupType || '3';
    //     // this.sqlSpliceType = this.fundDynamicGroupBounds.sqlSpliceType + ' ' + this.Dict.conditionRelation[this.fundDynamicGroupBounds.sqlSpliceType];
    //     this.originListlist = await DictionConstUtil.FNBoundCfg();
    //     // 获取范围配置信息
    //     this.originList = this.originListlist
    //         .filter(item => item.boundCode !== 'YH011' && item.boundType === this.investGroupType && item.validSymbol === '1')
    //         .sort((a, b) => a.boundCode.replace(/[^0-9]/gi, '') - b.boundCode.replace(/[^0-9]/gi, ''));
    // }

    @Watch('stockBound', { immediate: true, deep: true })
    watchStockBound() {
        let stockBound = [];
        if (this.stockBound) {
            stockBound = this.stockBound;
        } else {
            stockBound = [];
        }
        // 获取范围配置信息
        this.originList = this.originListlist
            .filter(item => item.boundCode !== 'YH011' && item.boundType === this.investGroupType && item.validSymbol === '1')
            .sort((a, b) => a.boundCode.replace(/[^0-9]/gi, '') - b.boundCode.replace(/[^0-9]/gi, ''));
        // 配置数据集合
        this.originalConfigList = JSON.parse(JSON.stringify(stockBound));
        // 处理操作类型
        this.operateBoundCfg(this.operateType, this.originalConfigList);
        // 设置值
        this.fundDynamicGroupBounds.groupType = this.investGroupType || '3';
        this.sqlSpliceType = this.fundDynamicGroupBounds.sqlSpliceType + ' ' + this.Dict.conditionRelation[this.fundDynamicGroupBounds.sqlSpliceType];
        // this.showType = this.fxType;
    }

    // 监听范围类型
    @Watch('investGroupType', { immediate: true, deep: true })
    async changGroupType() {
        // 获取范围配置信息
        console.log(this.originListlist, 'this.originListlist');
        // this.originList = await DictionConstUtil.FNBoundCfgByBoundType(this.investGroupType);
        // this.originList = this.originListlist
        //     .filter(item => item.boundCode !== 'YH011' && item.boundType === this.investGroupType && item.validSymbol === '1')
        //     .sort((a, b) => a.boundCode.replace(/[^0-9]/gi, '') - b.boundCode.replace(/[^0-9]/gi, ''));
        // 清空数据
        this.fundDynamicGroupBounds = {
            dynamicCode: '',
            boundCode: '-1',
            boundValues: [],
            compareType: '',
            boundValueNames: [],
            boundGroupValid: true,
            parentId: 0,
            configId: 2,
            separateValid: false,
            showBoundExtend: false,
            specialBranch: false,
            sqlSpliceType: '0',
            groupType: this.investGroupType || '3',
        };
        this.sqlSpliceType = '0 并且';
        this.originalConfigList = [];
        this.originalRenderTree = [];
        // this.handleRenderTree(this.originalConfigList);
    }

    @Watch('riskEntryBranchList', { immediate: true, deep: true })
    async watchRiskEntryBranchList() {
        this.originList = await DictionConstUtil.FNBoundCfgByBoundType(this.investGroupType);
        let configId = null;
        let riskEntryBranchList = this.riskEntryBranchList;
        let newArr = [];
        if (riskEntryBranchList.length > 0) {
            for (let i = 0; i < riskEntryBranchList.length; i++) {
                newArr.push(riskEntryBranchList[i].configId);
            }
            configId = Math.max.apply(null, newArr);
            this.configId = configId + 1;
        }

        this.originalConfigList = JSON.parse(JSON.stringify(this.riskEntryBranchList));
        this.originalRenderTree = this.handleRenderTree(this.originalConfigList);
        this.onHandleSettingValue(this.originalConfigList);
    }

    // 传来的操作状态;
    private operateBoundCfg(operateType: string, stockBound: any): void {
        if (operateType === 'look' || operateType === 'edit') {
            let configId = 3;
            for (let i = 0; i < stockBound.length; i++) {
                if (stockBound[i].boundGroupValid) {
                    stockBound[i].compareType = '';
                    stockBound[i].boundCode = '-1';
                }
                if (configId < stockBound[i].configId) {
                    // 获得最大的configId
                    configId = stockBound[i].configId;
                }
            }
            this.configId = configId + 1;
            // 节点渲染 默认展开所有的节点
            this.allParentTreeNodes = [];
            this.originalRenderTree = this.handleRenderTree(stockBound);

            this.currentOpenTreeNode = this.allParentTreeNodes;
        }
    }

    // 证券范围配置下拉列表框改变时 触发该事件
    private handleOriginalBoundConfig(val: string): void {
        this.fundDynamicGroupBounds.dynamicCode = '';
        this.fundDynamicGroupBounds.separateValid = false;
        this.fundDynamicGroupBounds.showBoundExtend = false;
        this.fundDynamicGroupBounds.specialBranch = false;
        this.fundDynamicGroupBounds.groupType = this.investGroupType || '3';
        this.fundDynamicGroupBounds.boundCode = val;
        this.fundDynamicGroupBounds.compareType = '';
        this.fundDynamicGroupBounds.boundValues = [];
        this.fundDynamicGroupBounds.boundValueNames = [];
        this.clearBoundFormColumn(this.webShowType);
        this.webShowType = '';
        this.compareTypes = [];
        this.currentConfigSeparateValid = false;
        this.separateValid = false;
        this.boundValueShow = '';
        if (this.fundDynamicGroupBounds.boundCode === '-1') {
            this.fundDynamicGroupBounds.boundGroupValid = true;
            this.webShowType = '';
            this.compareTypes = [];
            this.currentConfigSeparateValid = false; // 当前范围是否支持同申报
            this.separateValid = false;
        } else {
            this.fundDynamicGroupBounds.boundGroupValid = false;
            this.originList.forEach(element => {
                if (element.boundCode === val) {
                    this.compareTypes = element.webDirections;
                    this.webShowType = element.webShowType;
                    if (this.webShowType === '0') {
                        // 多选
                        this.handleShowWebShow(val);
                    } else if (this.webShowType === '4') {
                        // 单选
                        this.handleShowWebShow(val);
                    }
                }
            });
        }
        this.$forceUpdate();
    }

    //  根据证券范围配置编号获取 展示SQL
    private handleShowWebShow(boundCode) {
        if (boundCode === '-1') {
            return;
        }
        this.dicts = [];
        return new Promise(resolve => {
            this.$axios.get('/original/showSelect/' + boundCode).then(
                (res: any) => {
                    if (res) {
                        this.dicts = res;
                        this.dictsTemp = this.dicts;
                        resolve('success'); //
                    }
                },
                () => {
                    this.dicts = [];
                    this.dictsTemp = [];
                    resolve('fail');
                }
            );
        });
    }

    // 将范围属性表单字段置空
    private clearBoundFormColumn(webShowType: string) {
        if (webShowType === '1' || webShowType === '5') {
            this.form.boundValueNum = undefined;
        } else if (webShowType === '4') {
            this.boundValueSelect = '';
        } else if (webShowType === '3') {
            this.boundValueDate = '';
        }
    }

    // 触发下拉框 webShowType === '0'
    private showTypeFocusEvent(): void {
        this.boundValueSearchInput = '';
        this.dictsTemp = this.dicts;
        (this.$refs as any).showTypeDown.showPanel();
    }

    // 范围配置下拉框搜索
    private boundValueSearch(): void {
        this.dictsTemp =
            this.boundValueSearchInput !== ''
                ? this.dicts.filter(element => {
                      return element.dictKey.indexOf(this.boundValueSearchInput) > -1 || element.dictKeyName.indexOf(this.boundValueSearchInput) > -1;
                  })
                : this.dicts;
    }

    // 多选框类型---下拉框选择改变处理
    private handleBoundValueChange(checkedData): void {
        let i = 0;
        this.boundValueShow = '';
        this.fundDynamicGroupBounds.boundValueNames = [];
        checkedData.forEach(element => {
            this.dictsTemp.forEach(item => {
                if (element === item.dictKey) {
                    this.boundValueShow = this.boundValueShow + element + '(' + item.dictKeyName + ')';
                    this.fundDynamicGroupBounds.boundValueNames.push(item.dictKeyName);
                }
            });
            i++;
            if (i < checkedData.length) {
                this.boundValueShow = this.boundValueShow + ',';
            }
        });
    }

    // 点击节点
    private handleBoundNodeClick(keys: any) {
        this.fundDynamicGroupBounds = {};
        this.webShowType = '';
        this.compareTypes = [];
        this.separateValid = false; // 是否支持同申报
        if (!keys.configId) {
            return;
        }

        if (this.currentTreeNode === keys.configId) {
            this.originalRenderTree = JSON.parse(JSON.stringify(this.originalRenderTree)); //
            this.currentTreeNode = '';
            // 第二次点击
            this.rightTranData = [];
            this.fundDynamicGroupBounds = {
                dynamicCode: '',
                boundCode: '-1',
                boundValues: [],
                compareType: '',
                boundValueNames: [],
                boundGroupValid: true,
                parentId: 0,
                configId: 2,
                separateValid: false,
                sqlSpliceType: '0',
                groupType: this.investGroupType || '3',
            };
            this.sqlSpliceType = '0 并且';
        } else {
            // 第一次点击
            this.currentTreeNode = keys.configId;
            let orgBound = this.originalConfigList.find(item => String(item.configId) === keys.configId);
            this.sqlSpliceType = orgBound.sqlSpliceType + ' ' + this.Dict.conditionRelation[orgBound.sqlSpliceType];
            this.fundDynamicGroupBounds = JSON.parse(JSON.stringify(orgBound));
            if (orgBound.boundGroupValid) {
                // 组配置
                this.webShowType = '';
                this.compareTypes = [];
                this.separateValid = false;
            } else {
                let orgCfg = this.originList.find(item => item.boundCode === orgBound.boundCode);
                this.webShowType = orgCfg.webShowType;
                this.compareTypes = orgCfg.webDirections || [];
                this.separateValid = orgCfg.separateValid;
                // 如果为下拉列表时 需要加载下拉列表数据
                if (this.webShowType === '0') {
                    this.handleShowWebShow(orgBound.boundCode).then(() => {
                        this.handleBoundValueChange(this.fundDynamicGroupBounds.boundValues);
                    });
                } else if (this.webShowType === '4') {
                    this.handleShowWebShow(orgBound.boundCode).then(() => {
                        this.boundValueSelect = this.fundDynamicGroupBounds.boundValues.toString();
                    });
                } else if (this.webShowType === '1') {
                    this.form.boundValueNum = parseInt(this.fundDynamicGroupBounds.boundValueNames.toString());
                } else if (this.webShowType === '5') {
                    this.form.boundValueNum = parseFloat(this.fundDynamicGroupBounds.boundValueNames.toString());
                } else if (this.webShowType === '2') {
                    this.rightTranData = this.fundDynamicGroupBounds.boundValues.map((dictKey, i) => ({
                        dictKey,
                        dictKeyName: this.fundDynamicGroupBounds.boundValueNames[i],
                    }));
                    this.transValuesShow = this.fundDynamicGroupBounds.boundValueNames.toString();
                } else if (this.webShowType === '3') {
                    this.boundValueDate = this.fundDynamicGroupBounds.boundValueNames.toString();
                }
            }
        }
    }

    // 处理范围属性的添加
    private handleAddConfig(): void {
        let dynamicOriginalConfigPO: dynamicDataReqVO = JSON.parse(JSON.stringify(this.fundDynamicGroupBounds));
        let isAdopt = this.verifySingleConfig(dynamicOriginalConfigPO);
        if (!isAdopt) {
            return;
        }
        let orgBound = this.originalConfigList.find(item => String(item.configId) === this.currentTreeNode) || { boundGroupValid: true };
        let parentId = 0;
        if (this.currentTreeNode && orgBound.boundGroupValid) {
            parentId = Number(this.currentTreeNode);
        }
        dynamicOriginalConfigPO.configId = this.configId;
        dynamicOriginalConfigPO.parentId = parentId;
        this.originalConfigList.push(dynamicOriginalConfigPO);
        // 设置configId递增
        this.configId += 1;
        this.originalRenderTree = this.handleRenderTree(this.originalConfigList);
        if (this.currentTreeNode && orgBound.boundGroupValid) {
            this.currentOpenTreeNode.push(this.currentTreeNode);
        }
        this.handleOriginalBoundConfig('-1'); // -1相当于是重新进行清空操作
        // 回调函数
        this.onHandleSettingValue(this.originalConfigList);
    }

    // 更新配置项
    private handleUpdateConfig(): void {
        if (!this.currentTreeNode) {
            this.yh_message_warn('请选择节点进行操作');
            return;
        }
        let index;
        let orgBound = this.originalConfigList.find((item, i) => {
            index = i;
            return String(item.configId) === this.currentTreeNode;
        });
        if (orgBound.boundGroupValid) {
            this.yh_message_warn('组节点不允许进行修改');
            return;
        }
        // 证券范围信息
        let dynamicOriginalBoundConfigPO = JSON.parse(JSON.stringify(this.fundDynamicGroupBounds));
        let isAdopt = this.verifySingleConfig(dynamicOriginalBoundConfigPO);
        if (!isAdopt) {
            return;
        }
        // 设置 configId 和 parentId
        dynamicOriginalBoundConfigPO.configId = orgBound.configId;
        dynamicOriginalBoundConfigPO.parentId = orgBound.parentId;
        this.originalConfigList.splice(index, 1, dynamicOriginalBoundConfigPO);
        this.originalRenderTree = this.handleRenderTree(this.originalConfigList);
        // 回调函数
        this.onHandleSettingValue(this.originalConfigList);
    }

    // 删除证券范围配置
    private handleDeleteConfig(): void {
        if (!this.currentTreeNode) {
            this.yh_message_warn('请选择节点进行删除');
            return;
        }
        if (this.handleRenderListTree.length === 1) {
            this.yh_message_warn('删除全部配置将会是无效操作,如有必要,可直接该删除账户组');
        }
        let newList = [];
        newList.push(Number(this.currentTreeNode));
        this.handleSearchConfigId(this.originalConfigList, Number(this.currentTreeNode), newList);
        for (let i = 0; i < this.originalConfigList.length; i++) {
            if (newList.includes(this.originalConfigList[i].configId)) {
                this.originalConfigList.splice(i, 1);
                i--;
            }
        }
        this.originalRenderTree = this.handleRenderTree(this.originalConfigList);
        this.currentTreeNode = ''; //

        // 回调函数
        this.onHandleSettingValue(this.originalConfigList);
    }

    // 查找 configId 下的范围  用于删除节点
    private handleSearchConfigId(orginalList: any, configId: number, newList: any[]) {
        for (let i = 0; i < orginalList.length; i++) {
            if (orginalList[i].parentId === configId) {
                if (orginalList.map(item => item.parentId).includes(orginalList[i].configId)) {
                    this.handleSearchConfigId(orginalList, orginalList[i].configId, newList);
                }
                newList.push(orginalList[i].configId);
            }
        }
    }

    // 设置回调
    private onHandleSettingValue(list) {
        if (this.operateType === 'look') {
            return;
        }
        let settingValue = JSON.parse(JSON.stringify(list));
        for (let i = 0; i < settingValue.length; i++) {
            // 父节点设置
            if (settingValue[i].boundGroupValid) {
                settingValue[i].boundCode = '';
                settingValue[i].compareType = '4';
            }
        }
        this.settingValue(settingValue); // 调用父组件方法
    }

    // 将集合创建成树
    private handleRenderTree(stockBound) {
        let stockConfig = JSON.parse(JSON.stringify(stockBound));
        let treeList = this.createTreeList(stockConfig, 0);
        let value = this.handleRenderListTree(treeList);
        return value;
    }

    // 列表组装成树形集合
    private createTreeList(orginalList, configId): any {
        let newList = [];
        for (let i = 0; i < orginalList.length; i++) {
            if (orginalList[i].parentId === configId) {
                if (orginalList.find(item => item.parentId === orginalList[i].configId)) {
                    orginalList[i].children = this.createTreeList(orginalList, orginalList[i].configId);
                }
                newList.push(orginalList[i]);
            }
        }
        return newList;
    }

    // 范围配置 树形集合转化成渲染树(显示树)
    private handleRenderListTree(treeList: any) {
        return treeList.map(item => {
            // 处理节点名称
            // debugger;

            let sqlSpliceTypeName = this.conditionRelation[item.sqlSpliceType];
            let boundName = '';
            let compareTypeName = '';
            let boundValueNames = '';
            // 组配置
            if (item.boundGroupValid) {
                boundName = '';
                compareTypeName = '';
                boundValueNames = '';
            } else if (item.separateValid) {
                let orgCfg = this.originList.find(item1 => item.boundCode === item1.boundCode);
                for (let i = 0; i < this.originList.length; i++) {
                    if (item.boundCode == this.originList[i].boundCode) {
                        boundName = this.originList[i].boundName;
                    }
                }
                compareTypeName = this.CompareDirection[item.compareType];
                boundValueNames = '单独控制';
            } else {
                let orgCfg = this.originList.find(item1 => item.boundCode === item1.boundCode);
                for (let i = 0; i < this.originList.length; i++) {
                    if (item.boundCode == this.originList[i].boundCode) {
                        boundName = this.originList[i].boundName;
                    }
                }
                compareTypeName = this.CompareDirection[item.compareType];
                boundValueNames = item.boundValueNames || item.boundValues || '';
            }
            let title = sqlSpliceTypeName + ' ' + boundName + ' ' + compareTypeName + ' ' + boundValueNames;
            // 渲染时记录所有的父级节点
            if (item.boundGroupValid) {
                this.allParentTreeNodes.push(String(item.configId));
            }
            // 存在子节点
            if (item.children && item.children.length > 0) {
                item.children = this.handleRenderListTree(item.children);
            }
            return Object.assign(item, {
                label: title,
                configId: String(item.configId),
            });
        });
    }

    // 校验配置的范围信息
    private verifySingleConfig(dynamicOriginalConfigPO): boolean {
        // 添加空组时
        if (dynamicOriginalConfigPO.boundCode === '-1') {
            return true;
        } else if (dynamicOriginalConfigPO.separateValid === true) {
            return true;
        } else {
            if (!dynamicOriginalConfigPO.boundValues || dynamicOriginalConfigPO.boundValues.length === 0) {
                this.yh_message_info('未配置范围属性的值');
                return false;
            }
            if (!dynamicOriginalConfigPO.compareType) {
                this.yh_message_info('未配置比较方向');
                return false;
            }
            return true;
        }
    }

    // sql拼接字符串
    private handleSqlSpliceType(value: string): void {
        this.fundDynamicGroupBounds.sqlSpliceType = value.split(' ')[0];
    }

    // 计数器类型
    private handleBoundValueChange1(num: number): void {
        this.webShowType == '1' && (num = Math.round(num));
        this.fundDynamicGroupBounds.boundValues = [];
        this.fundDynamicGroupBounds.boundValueNames = [];
        this.fundDynamicGroupBounds.boundValues.push(num.toString());
        this.fundDynamicGroupBounds.boundValueNames.push(num.toString());
    }

    // 日期类型
    public handleBoundValueChange2(date) {
        this.fundDynamicGroupBounds.boundValues = [];
        this.fundDynamicGroupBounds.boundValueNames = [];
        this.fundDynamicGroupBounds.boundValues.push(date);
        this.fundDynamicGroupBounds.boundValueNames.push(date);
    }

    // 选择器类型
    private handleBoundValueChange3(value: any): void {
        this.fundDynamicGroupBounds.boundValues = [];
        this.fundDynamicGroupBounds.boundValueNames = [];
        this.fundDynamicGroupBounds.boundValues.push(value);
        this.dictsTemp.forEach(ele => {
            if (ele.dictKey === value) {
                this.fundDynamicGroupBounds.boundValueNames.push(ele.dictKeyName);
                return;
            }
        });
    }

    // 大数据穿梭框--弹框
    private selectKeyValue2Click(): void {
        this.editLargeDataDialog = this.editLargeDataDialog.getAddDialog('');
        this.transValuesShow = this.fundDynamicGroupBounds.boundValueNames.toString();
        this.$axios
            .post('/original/showBigData', {
                boundCode: this.fundDynamicGroupBounds.boundCode,
                categorys: [],
                filterCodes: this.fundDynamicGroupBounds.boundValues,
                keyName: '',
                leftSearchPrecision: false,
                paging: { currentPage: 1, pageSize: 20 },
            })
            .then((res: any) => {
                this.leftTranData = res.list;
                this.rightTranData = this.getRightTranData(this.fundDynamicGroupBounds);
            });
    }

    private getRightTranData(values): any {
        let arr: any[] = [];
        for (let i = 0; i < values.boundValues.length; i++) {
            arr.push({ dictKey: values.boundValues[i], dictKeyName: values.boundValueNames[i] });
        }
        return arr;
    }

    // 大数据弹窗确认
    private editLargeDataDialogConfirm(): void {
        let needData = [];
        const rightData = (this.$refs.tranTable as any).getRightAllData();
        this.fundDynamicGroupBounds.boundValues = XEUtils.map(rightData, item => item.dictKey);
        this.fundDynamicGroupBounds.boundValueNames = XEUtils.map(rightData, item => item.dictKeyName);
        this.transValuesShow = this.fundDynamicGroupBounds.boundValueNames.toString();
        this.editLargeDataDialogClosed();
    }

    // 关闭弹窗
    private editLargeDataDialogClosed(): void {
        this.editLargeDataDialog.visible = false;
    }
}
</script>
<style lang="scss" scoped>
.risk-bound-cfg {
    border: 1px solid #cacaca;
    border-radius: 5px;
    background-color: #ebebeb;
    padding: 2px 0;
}
.risk-bound-tree {
    border: 1px solid #cacaca;
    border-radius: 5px;
    margin: 5px 0;
    background-color: #f5f5f5;
    .risk-bound-tree-show {
        height: 300px;
        margin-top: 5px;
    }
}
.my-dropdown {
    height: 160px;
    overflow: auto;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    .accountControlValue-search {
        width: 98%;
        height: 30px;
        margin: 2px 5px;
        .input-container {
            display: inline-block;
            width: 90%;
        }
    }
    /deep/ .el-checkbox {
        display: block;
        margin-left: 5px;
        line-height: 10px;
    }
}
/deep/ .el-button + .el-button {
    margin: 0px;
}
/deep/ .el-tree {
    width: fit-content;
    .el-tree-node.is-current > .el-tree-node__content {
        background: transparent;
        & > span:last-child {
            background: #bae7ff;
            color: #415159;
        }
    }
    .el-tree-node__content {
        background: transparent;
        &:hover {
            & > span:last-child {
                background: #e6f7ff;
                color: #415159;
            }
        }
    }
}
/deep/ .el-tree__empty-text {
    position: static;
}
/deep/ .el-button--mini,
.el-button--mini.is-round {
    padding: 6px 15px;
}
</style>
